package org.ocean.online.sys;

import java.util.Hashtable;
import java.util.Properties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.pages.RedirectPage;
import org.apache.wicket.model.Model;
import org.ocean.online.wicket.BaseWebPage;

public class SimpleInitPage extends BaseWebPage{
	private static final long serialVersionUID = 3836897575091055641L;

	private HiddenField<String> propsJson= new HiddenField<String>("propsJson",new Model<String>());
	public SimpleInitPage(){
		Form<?> form = new Form("form",new Model());
		add(form);
		form.add(propsJson);
		
		
		Properties props = OnlineConfig.getProps();
		props.remove("initd");
		props.remove("projectType");
		
//		props.put("dbType", "h2");
//		props.put("url", "");
//		props.put("username", "");
//		props.put("password", "");
//		props.put("initd", "false");
//		props.put("projectType", "simple");
		
		JSONArray jsonArr = new JSONArray();
		JSONObject jobj = new JSONObject();
		for(Object key:props.keySet()){
			JSONObject prop = new JSONObject();	
			prop.put("name", key);
			prop.put("value", props.get(key));
			prop.put("editor", "text");
			jsonArr.add(prop);
		}
		
		jobj.put("rows", jsonArr);
		propsJson.setDefaultModelObject(jobj.toString());
		
		AjaxSubmitLink link = new AjaxSubmitLink("submit",form) {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				JSONObject jobj = JSONObject.fromObject(propsJson.getDefaultModelObjectAsString());
				JSONArray arr = (JSONArray) jobj.get("rows");
				for(int i=0;i<arr.size();i++){
					jobj = arr.getJSONObject(i);
					OnlineConfig.put(jobj.get("name"), jobj.get("value"));
				}
				OnlineConfig.put("initd", "true");
				OnlineConfig.save();
				setResponsePage(new RedirectPage("/"+OnlineConfig.getProperty("appName")));
				
			}
		};
		form.add(link);
	}
}
